﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZG_member.BLL;
using System.IO;
using System.Text.RegularExpressions;
using System.Configuration;

namespace ZG_member
{
    public partial class LoseCardForm : Form
    {
        MainForm main;
        string memid = "0";
        string memberIds = "0";
        public LoseCardForm(MainForm mm, string idd,string memberId, VisualCardPrinter_NPPrinter_New.VisualCardPrinter_NPPrinter pss)
        {
            InitializeComponent();
            main = mm;
            this.Opacity = 0;
            vnp = pss;
            memid = idd;
            memberIds = memberId;
            skinEngine1.SkinFile = Application.StartupPath + ConfigurationManager.AppSettings["Skin"];

        }
        VisualCardPrinter_NPPrinter_New.VisualCardPrinter_NPPrinter vnp;
        public static bool pass = false;
        private void readCardBtn_Click(object sender, EventArgs e)
        {

            if (txtMemberid.Text != "")
            {
                memberInfo memInfo = new memberInfo();
                Model.memberInfo memInfoModel = new Model.memberInfo();
                memInfoModel = memInfo.GetModels(txtMemberid.Text);
                if (memInfoModel == null)
                {
                    MessageBox.Show("输入有误！没有找到该会员");
                    return;
                }
                txtBalance.Text = (memInfoModel.Balance == null ? 0 : memInfoModel.Balance).ToString();
                txtIDNumber.Text = (memInfoModel.IDNumber == null ? "" : memInfoModel.IDNumber).ToString();
                txtPoint.Text = (memInfoModel.point == null ? 0 : memInfoModel.point).ToString();
                txtmembername.Text = memInfoModel.memberName.ToString();

            }
        }

        private void LoseCardForm_Load(object sender, EventArgs e)
        {
            this.timer1.Start();
            this.label3.ForeColor = Color.Red;
            dgvMemberInfo.AllowUserToAddRows = false;
            dgvmenberinfo();
            if (memberIds != "0")
            {
                this.txtMemberid.Text = memberIds;
                if (txtMemberid.Text != "")
                {
                    memberInfo memInfo = new memberInfo();
                    Model.memberInfo memInfoModel = new Model.memberInfo();
                    memInfoModel = memInfo.GetModels(memberIds);
                    this.txtMemberid.Text = memInfoModel.memberId;
                    if (memInfoModel == null)
                    {
                        MessageBox.Show("输入有误！没有找到该会员");
                        return;
                    }
                    txtBalance.Text = (memInfoModel.Balance == null ? 0 : memInfoModel.Balance).ToString();
                    txtIDNumber.Text = (memInfoModel.IDNumber == null ? "" : memInfoModel.IDNumber).ToString();
                    txtPoint.Text = (memInfoModel.point == null ? 0 : memInfoModel.point).ToString();
                    txtmembername.Text = memInfoModel.memberName.ToString();

                }
            }
        }
        private void dgvmenberinfo()
        {
            memberInfo memInfo = new memberInfo();
            StringBuilder sb = new StringBuilder();
            sb.Append("status='" + 1 + "'");
            sb.Append("or" + " ");
            sb.Append("status='" + 2 + "'");
            DataTable dt = memInfo.GetList(sb.ToString()).Tables[0];
            dgvMemberInfo.DataSource = dt;

            foreach (DataGridViewRow dgvr in dgvMemberInfo.Rows)
            {
                if (dgvr.Cells["sex"].Value != null)
                {
                    if (dgvr.Cells["sex"].Value + "" == "False")
                    {
                        dgvr.Cells["sexName"].Value = "女";
                    }
                    else
                    {
                        dgvr.Cells["sexName"].Value = "男";
                    }
                }
                if (dgvr.Cells["status"].Value != null)
                {
                    if (dgvr.Cells["status"].Value + "" == "正常")
                    {
                        dgvr.Cells["Newstatus"].Value = "正常";
                    }
                    if (dgvr.Cells["status"].Value + "" == "挂失")
                    {
                        dgvr.Cells["Newstatus"].Value = "挂失";
                    }
                    if (dgvr.Cells["status"].Value + "" == "停用")
                    {
                        dgvr.Cells["Newstatus"].Value = "停用";
                    }
                }
                consumeSolution consume = new consumeSolution();
                Model.consumeSolution consumeMod = new Model.consumeSolution();
                if (dgvr.Cells["cardType"].Value != null)
                {
                    int ID = int.Parse(dgvr.Cells["cardType"].Value.ToString());
                    consumeMod = consume.GetModelList("id='" + ID + "'")[0];
                    dgvr.Cells["NewcardType"].Value = consumeMod.solutionName;
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.timer2.Start();
        }

        private void btnlose_Click(object sender, EventArgs e)
        {
            if (txtMemberid.Text != "")
            {
                LoseCardPass lcp = new LoseCardPass(this.txtMemberid.Text);
                lcp.ShowDialog();
                if (pass != true)
                {
                    MessageBox.Show("密码验证失败");
                    return;
                }
                pass = false;
                memberInfo memInfo = new memberInfo();
                Model.memberInfo memInfoModel = new Model.memberInfo();
                //memInfoModel = memInfo.GetGuaShi("memberCardId='" + txtmemberCarId.Text + "'")[0];
                memInfoModel = memInfo.GetModels(txtMemberid.Text);
                memInfoModel.status = 1;
                if (memInfo.Update(memInfoModel))
                {
                    // MessageBox.Show("挂失成功!"); 
                    dgvmenberinfo();
                }
            }
        }

        private void stopUsedBtn_Click(object sender, EventArgs e)
        {
            if (txtMemberid.Text != "")
            {
                LoseCardPass lcp = new LoseCardPass(this.txtMemberid.Text);
                lcp.ShowDialog();
                if (pass != true)
                {
                    MessageBox.Show("密码验证失败");
                    return;
                }
                pass = false;
                memberInfo memInfo = new memberInfo();
                Model.memberInfo memInfoModel = new Model.memberInfo();
                memInfoModel = memInfo.GetModels(txtMemberid.Text);
                memInfoModel.status = 2;
                if (memInfo.Update(memInfoModel))
                {
                    //  MessageBox.Show("停用成功!");
                    dgvmenberinfo();
                }
            }
        }
        int retu;
        string Number;
        private void exchangeCardBtn_Click(object sender, EventArgs e)
        {
          
            
            pass = false;
            string memberId = this.txtMemberid.Text;
            ZG_member.Model.memberInfo memMode = new ZG_member.Model.memberInfo();
            memberInfo mem = new memberInfo();
            memMode = mem.GetModels(memberId);
            if (memMode.pwd != null && memMode.pwd != "")
            { 
                LoseCardPass lcp = new LoseCardPass(this.txtMemberid.Text);
                lcp.ShowDialog();
                if (pass != true)
                {
                    MessageBox.Show("密码验证失败");
                    return;
                }
            }
            memMode.memberCardId = GetNumber(DateTime.Now.ToString());


            if (mem.Update(memMode))
            {
                //  MessageBox.Show("停用成功!");
                dgvmenberinfo();
            }
            //写卡
            //byte[] printer = System.Text.Encoding.Default.GetBytes(ConfigurationManager.AppSettings["printer"]);
            //int x = Convert.ToInt32(ConfigurationManager.AppSettings["X"]);
            //int y = Convert.ToInt32(ConfigurationManager.AppSettings["Y"]);
            //int direction = Convert.ToInt32(ConfigurationManager.AppSettings["direction"]);
            //byte[] fontname = System.Text.Encoding.Default.GetBytes(ConfigurationManager.AppSettings["Font"]);
            //int fontsize = int.Parse(ConfigurationManager.AppSettings["Font-Size"]);

            //VisualCardPrinter_NPPrinter.VisualCardPrinter_NPPrinter vp = new VisualCardPrinter_NPPrinter.VisualCardPrinter_NPPrinter(
            //    1, 57600, printer, x, y, direction, fontname, fontsize, ref retu);
            //string date = DateTime.Now.ToString();
            string contents = memMode.memberCardId;
            string mima;
            try
            {
                mima = vnp.ZSGW_KeyPass(vnp.RfidCardRequestAndReadNum());
                vnp.RfidCardRequestAndWriteData("1", mima, contents);
            }
            catch (Exception)
            {

                MessageBox.Show("此卡不是本公司的卡片！请与本公司联系。电话：010-51291008");
                return;
            }


            //vnp.RfidCardRequestAndWriteData("1", "FFFFFFFFFFFF", contents);
            MemberSaleForm ms = new MemberSaleForm(main,memMode.memberCardId, this.txtMemberid.Text, vnp);
            ZG_member.Model.memberInfo memberMode = new ZG_member.Model.memberInfo();
            memberMode = mem.GetModels(memberId);
            ZG_member.BLL.consumeSolution cons = new ZG_member.BLL.consumeSolution();
            ZG_member.Model.consumeSolution consMode = new ZG_member.Model.consumeSolution();
            consMode = cons.GetModel(Convert.ToInt32(memberMode.cardType));
            string sexStr = "";
            if (memberMode.sex == true)
            {
                sexStr = "男";
            }
            else
            {
                sexStr = "女";
            }
            string status = "";
            if (memberMode.status == 0)
            {
                status = "正常";
            }
            else if (memberMode.status == 1)
            {
                status = "挂失";
            }
            else if (memberMode.status == 2)
            {
                status = "停用";
            }
            string Balance = (Convert.ToDecimal(memberMode.Balance.Value)).ToString("F1");
                                                       //"会员卡号#卡片类型                              #会员姓名#性　　别#卡片状态#办卡日期                                                                                          #截止日期                                                       #累计积分   #本次积分                     #可用积分#本次消费#储值余额#折扣金额#本次充值#积分支付#现金消费#空　　行";
            string[] ModelArray = new string[] { memberMode.memberId, consMode.solutionName, memberMode.memberName, sexStr, status, Convert.ToDateTime(memberMode.createDate.Value).ToString("yyyy-MM-dd"), Convert.ToDateTime(memberMode.expiresDate.Value).ToString("yyyy-MM-dd"), memberMode.point.Value.ToString(), "0", memberMode.point.Value.ToString(), "0", Balance, "0", "0", "0","0","" };
            string Go = ms.print(ModelArray);
            Go = "\n" + Go;
            vnp.PrintBufferClear();
            vnp.PrintCharacterDataSetting(Go);
            vnp.ErasePrintDischarge3();

            MessageBox.Show("换卡成功");
            //StreamReader sr = new StreamReader("nextCardNumber.ini", Encoding.GetEncoding("gb2312"));
            //if (sr.Peek() >= 0)
            //{
            //    Number = sr.ReadLine();
            //}
            //else
            //{
            //}
            //sr.Close();
            //string x;
            //x = (long.Parse(Number) + 1).ToString().PadLeft(11, '0');
            //StreamWriter sw = new StreamWriter("nextCardNumber.ini", false, Encoding.GetEncoding("gb2312"));
            //sw.Flush();
            //sw.Write(x);
            //sw.Close();

            //txtMemberid.Text = x;
            //if (txtmemberCarId.Text != "")
            //{
            //    memberInfo memInfo = new memberInfo();
            //    Model.memberInfo memInfoModel = new Model.memberInfo();
            //    memInfoModel = memInfo.GetModelList("memberCardId='" + txtmemberCarId.Text + "'")[0];
            //    memInfoModel.memberId = txtMemberid.Text;
            //    if (memInfo.Update(memInfoModel))
            //    {
            //      //  MessageBox.Show("换卡成功!");
            //        dgvmenberinfo();
            //    }
            //}

        }

        public static string GetNumber(string str)
        {
            string result = "0";
            if (str != null && str != string.Empty)
            {

                // 正则表达式剔除非数字字符（不包含小数点.）
                str = Regex.Replace(str, @"[^\d.\d]", "");
                // 如果是数字，则转换为decimal类型
                if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$"))
                {
                    result = str.ToString();
                }
            }
            return result;
        }
        private void normalBtn_Click(object sender, EventArgs e)
        {
            if (txtMemberid.Text != "")
            {
                LoseCardPass lcp = new LoseCardPass(this.txtMemberid.Text);
                lcp.ShowDialog();
                if (pass != true)
                {
                    MessageBox.Show("密码验证失败");
                    return;
                }
                pass = false;
                memberInfo memInfo = new memberInfo();
                Model.memberInfo memInfoModel = new Model.memberInfo();
                memInfoModel = memInfo.GetModels(txtMemberid.Text);
                memInfoModel.status = 0;
                if (memInfoModel.expiresDate <= DateTime.Now)
                {
                    memInfoModel.expiresDate = DateTime.Now.AddYears(1);
                }

                if (memInfo.Update(memInfoModel))
                {
                    //   MessageBox.Show("恢复成功!");-
                    dgvmenberinfo();
                }
            }
        }
        //更新主窗体信息
        private void LoseCardForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            main.shifouxianshi(MainForm.Operator);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Left += 2;
            this.Opacity += 0.1;
            if (Opacity == 1)
            {
                this.timer1.Stop();

            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            this.Top = this.Top + 10;
            this.Opacity = this.Opacity - 0.06;
            if (Opacity <= 0)
            {
                this.timer2.Stop();
                this.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.timer2.Start();
        }
        int flag = 0;
        private void LoseCardForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (flag == 0)
            {
                e.Cancel = true;
                flag = 1;
                this.timer2.Start();
            }
        }

        private void dgvMemberInfo_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            this.txtMemberid.Text = dgvMemberInfo.CurrentRow.Cells["memberId"].Value.ToString();
            this.txtPoint.Text = dgvMemberInfo.CurrentRow.Cells["point"].Value.ToString();
            this.txtmembername.Text = dgvMemberInfo.CurrentRow.Cells["memberName"].Value.ToString();
            this.txtIDNumber.Text = dgvMemberInfo.CurrentRow.Cells["IDNumber"].Value.ToString();
            this.txtBalance.Text = dgvMemberInfo.CurrentRow.Cells["Balance"].Value.ToString();
        }

        private void txtBalance_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
            {
                if (e.KeyChar == '.')
                {
                    if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                        e.Handled = true;
                }
                else
                    e.Handled = true;
            }
            else
            {
                if (e.KeyChar <= 31)
                {
                    e.Handled = false;
                }
                else if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                {
                    if (((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1).Length >= 4)
                        e.Handled = true;
                }
            }
        }

        private void txtIDNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
            {
                //if (e.KeyChar == '.')
                //{
                //    if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                //        e.Handled = true;
                //}
                //else
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar <= 31)
                {
                    e.Handled = false;
                }
                else if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                {
                    if (((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1).Length >= 4)
                        e.Handled = true;
                }
            }
        }

        private void txtMemberid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
            {
                //if (e.KeyChar == '.')
                //{
                //    if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                //        e.Handled = true;
                //}
                //else
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar <= 31)
                {
                    e.Handled = false;
                }
                else if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                {
                    if (((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1).Length >= 4)
                        e.Handled = true;
                }
            }
        }

        private void txtPoint_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
            {
                //if (e.KeyChar == '.')
                //{
                //    if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                //        e.Handled = true;
                //}
                //else
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar <= 31)
                {
                    e.Handled = false;
                }
                else if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                {
                    if (((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1).Length >= 4)
                        e.Handled = true;
                }
            }
        }


    }
}



